package com.eduhzy.ttw.work.mvp.ui.activity;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.widget.TextView;

import com.alibaba.android.arouter.facade.annotation.Autowired;
import com.alibaba.android.arouter.facade.annotation.Route;
import com.alibaba.android.arouter.launcher.ARouter;
import com.blankj.utilcode.util.ObjectUtils;
import com.blankj.utilcode.util.TimeUtils;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.eduhzy.ttw.commonres.activity.PicturePlayAudioActivity;
import com.eduhzy.ttw.commonres.activity.VideoPlayActivity;
import com.eduhzy.ttw.commonres.utils.RxUtil;
import com.eduhzy.ttw.commonres.view.AutoConstraintLayout;
import com.eduhzy.ttw.commonsdk.annotation.ScopeType;
import com.eduhzy.ttw.commonsdk.core.Constants;
import com.eduhzy.ttw.commonsdk.core.RouterHub;
import com.eduhzy.ttw.commonsdk.decoration.GridSpacingItemDecoration;
import com.eduhzy.ttw.commonsdk.holder.AutoBaseViewHolder;
import com.eduhzy.ttw.commonsdk.utils.MediaFile;
import com.eduhzy.ttw.work.R;
import com.eduhzy.ttw.work.R2;
import com.eduhzy.ttw.work.di.component.DaggerWorkDetailComponent;
import com.eduhzy.ttw.work.di.module.WorkDetailModule;
import com.eduhzy.ttw.work.mvp.contract.WorkDetailContract;
import com.eduhzy.ttw.work.mvp.model.entity.WorkDetailData;
import com.eduhzy.ttw.work.mvp.presenter.WorkDetailPresenter;
import com.eduhzy.ttw.work.mvp.ui.adapter.WorkFileAdapter;
import com.jess.arms.base.BaseActivity;
import com.jess.arms.di.component.AppComponent;
import com.jess.arms.utils.ArmsUtils;
import com.luck.picture.lib.PictureSelector;
import com.luck.picture.lib.entity.LocalMedia;
import com.luck.picture.lib.tools.DoubleUtils;
import com.qmuiteam.qmui.widget.QMUIEmptyView;
import com.qmuiteam.qmui.widget.dialog.QMUITipDialog;
import com.umeng.analytics.MobclickAgent;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.List;

import javax.inject.Inject;

import butterknife.BindView;

import static com.jess.arms.utils.Preconditions.checkNotNull;

/**
 * @author xubo
 * @date 2018-12-1 16:08:41
 */
@Route(path = RouterHub.WORK_WORKDETAILACTIVITY)
public class WorkDetailActivity extends BaseActivity<WorkDetailPresenter> implements WorkDetailContract.View {

    @BindView(R2.id.emptyView)
    QMUIEmptyView mEmptyView;
    @BindView(R2.id.tv_name)
    TextView mTvName;
    @BindView(R2.id.tv_title)
    TextView mTvTitle;
    @BindView(R2.id.tv_content)
    TextView mTvContent;
    @BindView(R2.id.rv_list2)
    RecyclerView mRvList2;
    @BindView(R2.id.tv_limited)
    TextView mTvLimited;
    @BindView(R2.id.tv_online)
    TextView mTvOnline;
    @BindView(R2.id.layout_title)
    AutoConstraintLayout mLayoutTitle;
    @BindView(R2.id.rv_list)
    RecyclerView mRvList;

    @Autowired(name = Constants.ROUTER_INTEGER)
    int workId;
    private WorkDetailData mData;

    @Inject
    WorkFileAdapter mFileAdapter;
    @Inject
    @ScopeType()
    RecyclerView.LayoutManager mFileManager;
    @Inject
    @ScopeType(2)
    RecyclerView.LayoutManager mClassManager;
    @Inject
    BaseQuickAdapter<WorkDetailData.HomeworkClassListBean, AutoBaseViewHolder> mClassAdapter;

    @Override
    public void setupActivityComponent(@NonNull AppComponent appComponent) {
        //如找不到该类,请编译一下项目
        DaggerWorkDetailComponent
                .builder()
                .appComponent(appComponent)
                .workDetailModule(new WorkDetailModule(this))
                .build()
                .inject(this);
    }

    @Override
    public int initView(@Nullable Bundle savedInstanceState) {
        MobclickAgent.onEvent(getActivity(),"ttw_work_detail");
        //如果你不需要框架帮你设置 setContentView(id) 需要自行设置,请返回 0
        return R.layout.work_activity_work_detail;
    }

    @Override
    public void initData(@Nullable Bundle savedInstanceState) {
        mEmptyView.show(true);
        mPresenter.detail4Teacher(workId);
    }

    @Override
    public void showLoading() {
        mEmptyView.show(true);
    }

    @Override
    public void hideLoading() {
        mEmptyView.hide();
    }

    @Override
    public void showMessage(@NonNull String message) {
        checkNotNull(message);
        RxUtil.showTipDialog(getActivity(), QMUITipDialog.Builder.ICON_TYPE_NOTHING, message);
    }

    @Override
    public void launchActivity(@NonNull Intent intent) {
        checkNotNull(intent);
        ArmsUtils.startActivity(intent);
    }

    @Override
    public void killMyself() {
        finish();
    }

    @Override
    public Activity getActivity() {
        return this;
    }

    @Override
    public void update(WorkDetailData data) {
        this.mData = data;
        mTvTitle.setText(data.getTitle());
        mTvName.setText(data.getCreatorName());
        mTvContent.setText(data.getContent());
        mTvLimited.setText(TimeUtils.millis2String(data.getEndTime(), new SimpleDateFormat("MM月dd日 HH:mm 截止")));
        mTvOnline.setVisibility(data.getOnline() == 1 ? View.VISIBLE : View.GONE);


        mRvList2.setLayoutManager(mFileManager);
        GridSpacingItemDecoration decoration = new GridSpacingItemDecoration(4, RxUtil.getAutoHeight(this, 15), false);
        mRvList2.addItemDecoration(decoration);
        mRvList2.setAdapter(mFileAdapter);
        mFileAdapter.getData().clear();
        List<LocalMedia> imgs = new ArrayList<>();
        if (ObjectUtils.isNotEmpty(data.getImageList())) {
            mFileAdapter.addData(data.getImageList());
            for (WorkDetailData.FileListBean bean : data.getImageList()) {
                LocalMedia media = new LocalMedia();
                media.setPath(bean.getUrl());
                imgs.add(media);
            }
        }
        if (ObjectUtils.isNotEmpty(data.getVideoList())) {
            mFileAdapter.addData(data.getVideoList());
        }
        if (ObjectUtils.isNotEmpty(data.getAudioList())) {
            mFileAdapter.addData(data.getAudioList());
        }
        mFileAdapter.setOnItemClickListener((adapter, view, position) -> {
            WorkDetailData.FileListBean item = mFileAdapter.getData().get(position);
            String mimeTypeForFile = MediaFile.getMimeTypeForFile(item.getName());
            int fileTypeForMimeType = MediaFile.getFileTypeForMimeType(mimeTypeForFile);

            if (MediaFile.isAudioFileType(fileTypeForMimeType)) {
                if (ObjectUtils.isEmpty(item.getUrl())) {
                    showMessage("音频转换中，请稍后");
                    mPresenter.detail4Teacher(workId);
                    return;
                }
                if (!DoubleUtils.isFastDoubleClick()) {
                    Intent intent = new Intent(this.getActivity(), PicturePlayAudioActivity.class);
                    intent.putExtra("audio_path", item.getUrl());
                    this.getActivity().startActivity(intent);
                    this.getActivity().overridePendingTransition(com.luck.picture.lib.R.anim.a5, 0);
                }
            } else if (MediaFile.isVideoFileType(fileTypeForMimeType)) {
                if (ObjectUtils.isEmpty(item.getUrl())) {
                    showMessage("视频转换中，请稍后");
                    mPresenter.detail4Teacher(workId);
                    return;
                }
                if (!DoubleUtils.isFastDoubleClick()) {
                    Intent intent = new Intent(this.getActivity(), VideoPlayActivity.class);
                    intent.putExtra(Constants.ROUTER_STRING, item.getUrl());
                    intent.putExtra(Constants.ROUTER_IMG, item.getPreimage());
                    this.getActivity().startActivity(intent);
                    this.getActivity().overridePendingTransition(com.luck.picture.lib.R.anim.a5, 0);
                }
//                PictureSelector.create(getActivity()).externalPictureVideo(item.getUrl());

            } else if (MediaFile.isImageFileType(fileTypeForMimeType)) {

                PictureSelector.create(getActivity()).themeStyle(R.style.picture_default_style).openExternalPreview(data.getImageList().indexOf(item), imgs);
            }
        });

        mRvList.setAdapter(mClassAdapter);
        mRvList.setLayoutManager(mClassManager);
        mClassAdapter.getData().clear();
        for (WorkDetailData.HomeworkClassListBean bean : data.getHomeworkClassList()) {
            bean.setOnline(data.getOnline());
            mClassAdapter.addData(bean);
        }
        mClassAdapter.setOnItemChildClickListener((adapter, view, position) -> {
            WorkDetailData.HomeworkClassListBean bean = mClassAdapter.getData().get(position);
            if (view.getId() == R.id.layout_unread) {
                ARouter.getInstance().build(RouterHub.WORK_WORKUNREADACTIVITY)
                        .withString(Intent.EXTRA_TITLE, "未阅读的同学(" + (bean.getTotalNum() - bean.getReadNum()) + ")")
                        .withInt(Constants.ROUTER_INTEGER, workId)
                        .withParcelable(Constants.PARCELABLE_DATA, bean)
                        .navigation(getActivity());
            } else {
                ARouter.getInstance().build(RouterHub.WORK_WORKSTATUSACTIVITY)
                        .withString(Intent.EXTRA_TITLE, "作业提交情况")
                        .withInt(Constants.ROUTER_INTEGER, workId)
                        .withParcelable(Constants.PARCELABLE_DATA, bean)
                        .navigation(getActivity());
            }
        });

    }

    @Override
    public void loadFail() {
        if (ObjectUtils.isNotEmpty(mEmptyView)) {
            mEmptyView.show(
                    false,
                    getResources().getString(R.string.public_emptyView_mode_desc_fail_title),
                    null,
                    getResources().getString(R.string.public_emptyView_mode_desc_retry),
                    v -> {
                        mPresenter.detail4Teacher(workId);
                    });

        }
    }

}